package nxu.contral;

import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import nxu.entity.Category;
import nxu.entity.Post;
import nxu.entity.comment;
import nxu.service.CategoryService;
import nxu.service.CommentService;
import nxu.service.PostService;


import java.util.List;

@Path(value = "/post" ,viewPath = "/post")
public class PostController extends Controller {
    private PostService postService= new PostService();
    private CategoryService categoryService = new CategoryService();
    private CommentService commentService= new CommentService();
    public void publish(){
        List<Category> categories= categoryService.findAll();
        set("categorys",categories);
        renderFreeMarker("publish.ftl");
    }


    public void save(){
        System.out.println("hhhh");
        String title = get("title","");
        String  cid = get("cid");
       // String pid = get("pid");
        String content = get("content");

        Post post = new Post();
        post.setCid(cid);
        post.setContent(content);
        post.setUid("1");
        post.setTitle(title);
        post.setPid("1");

        boolean success = postService.save(post);
        String message = success? "success":"error";
        renderHtml(message);
    }

    public void showAddCategory(){
        renderFreeMarker("addCategory.ftl");
    }
    public void addCategory(){
        String cid= get("cid");
        String cname=get("cname");

        boolean success = categoryService.addCategory(cid,cname);

        String message = success? "添加成功":"添加失败";
        renderHtml(message);
}


    public void listByCategory(){
        String cid= get("cid");
        System.out.println(cid);
       List<Post> posts= postService.listByCategory(cid);
       set("posts",posts);
       renderFreeMarker("listByCategory.ftl");
    }


    public void view(){
        String pid =get("pid");
        List<Post> posts=postService.view(pid);
        set("posts",posts);
        renderFreeMarker("view.ftl");
    }

    public void addComment(){
        String content = get("content");
        String pid = get("pid");
        comment com = new comment();
        com.setContent(content);
        com.setUid("1");
        com.setPid(pid);
        boolean success=commentService.addComment(com);
        String message = success? "添加成功":"添加失败";
        System.out.println(message);


        List<Post> posts=postService.view(pid);
        set("posts",posts);
        renderFreeMarker("view.ftl");

    }


    public void showComment(){
        String pid = get("pid");
        List<comment> comments= commentService.showComment(pid);
//        comment co= new comment();

        set("comments",comments);
        renderFreeMarker("showComment.ftl");
    }



}
